# -*- cod1ng:UTF-8 -*- #
"""
@filename:AI_可视化.py
@author:Liu Ru Qian
@time:2025-01-05
"""

from flask import Flask, request, jsonify
from openai import OpenAI
import os

app = Flask(__name__)

client = OpenAI(
    api_key="sk-oRwfsGJ7rT8fyPER24qT6C3XY8NamrhTPCUl7Xnn8dJumybh",  # 获取API密钥
    base_url="https://api.chatanywhere.tech/v1"
)

def gpt_35_api(messages: list):
    """为提供的对话消息创建新的回答"""
    try:
        completion = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages)
        return completion.choices[0].message.content
    except Exception as e:
        print("请求失败:", e)
        return "对不起，我无法处理您的请求。"


@app.route('/api/ask', methods=['POST'])
def ask_bot():
    """处理前端请求并返回AI的回答"""
    data = request.json  # 从请求中获取JSON数据
    messages = data.get('messages', [])

    # 检查 messages 是否为空
    if not messages:
        return jsonify({"error": "messages array is empty."}), 400

    # 获取模型的回复
    response = gpt_35_api(messages)

    # 返回JSON格式的响应
    return jsonify({"answer": response})


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)  # 运行Flask应用